const STS = require('qcloud-cos-sts');
const COS = require('cos-nodejs-sdk-v5');

const OSSConfig = {
  Bucket: 'manager-1300279250',
  Region: 'ap-chengdu'
};
const Secret = {
  SecretId: 'AKID92pNefAownzwd3A4TAaom4AzXrwkgZcQ',
  SecretKey: 'g5FBqEMEsEk01mGTQ8ZqVw71f3C4i6FJ'
};
/**
 * 授权策略
 * @param {String} LongBucketName 桶名
 * @param {String} Region 桶区域
 */
function policy(LongBucketName, Region) {
  let ShortBucketName = LongBucketName.substr(0, LongBucketName.indexOf('-'));
  let AppId = LongBucketName.substr(LongBucketName.indexOf('-') + 1);
  return {
    version: '2.0' /* 策略语法版本，默认为2.0 */,
    statement: [
      {
        action: [
          // 所有 action 请看文档 https://cloud.tencent.com/document/product/436/31923
          'name/cos:PutObject',
          'name/cos:GetObject'
          // // 分片上传
          // 'name/cos:InitiateMultipartUpload',
          // 'name/cos:ListMultipartUploads',
          // 'name/cos:ListParts',
          // 'name/cos:UploadPart',
          // 'name/cos:CompleteMultipartUpload',
          // 'name/cos:uploadFiles'
        ] /* 此处是指 COS API，根据需求指定一个或者一序列操作的组合或所有操作(*) */,
        effect: 'allow' /* 有 allow （允许）和 deny （显式拒绝）两种情况 */,
        principal: { qcs: ['*'] } /* 委托人 授权子账户权限 */,
        resource: ['qcs::cos:' + Region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/*'] /* 授权操作的具体数据，可以是任意资源、指定路径前缀的资源、指定绝对路径的资源或它们的组合 */
      }
    ]
  };
}
/**
 * 鉴权获取oss临时密钥接口
 * @param {*} res nuxt上下文对象
 * @param {*} req 执行下一步
 * @returns 返回临时密钥
 */
function getOssKey(req, res) {
  return new Promise(async (resolve, reject) => {
    try {
      // await jwt.verifyToken(ctx, next); /* 这里是对于用户访问进行鉴权，可以根据实际项目需求修改。 */
      STS.getCredential(
        {
          secretId: Secret.SecretId,
          secretKey: Secret.SecretKey,
          policy: policy(OSSConfig.Bucket, OSSConfig.Region),
          durationSeconds: 1
        },
        async (err, credential) => {
          // console.log(err || credential); // 这里拿到错误或者临时签名信息。
          return resolve((req.body = await res.send({
            code: 20000,
            data: err || credential
          })))
        }
      );
    } catch (error) {
      console.log('getOssKey:', error);
      return resolve(res.send({code: 10000}));
    }
  });
}

const deleteObject = (key, callback) => {
  cos.deleteObject({
    Bucket: OSSConfig.Bucket,
    Region: OSSConfig.Region,
    Key: key
  }, function (err, data) {
    err ? console.log(err) : callback(data)
  });
};
const cos = new COS(Secret);

function deleteFileAndPage(file, page , callback) {
  deleteObject(file, data => {});
  deleteObject(page, data => { callback(data) });
}



module.exports = {
  getOssKey,
  deleteFileAndPage
};
